package com.example.ssmp.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.example.ssmp.controller.utils.R;
import com.example.ssmp.domain.Book;
import com.example.ssmp.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController2 {

    @Autowired
    private IBookService bookService;

    @GetMapping
    public R getAll(){
        return new R(true,bookService.list());
    }

    @PostMapping
    public R save(@RequestBody Book book)throws IOException {

       boolean flag= bookService.save(book);
        return new R(flag,flag ? "添加成功" : "添加失败");
    }

    @PutMapping
    public R update(@RequestBody Book book)throws IOException {

        boolean flag= bookService.updateById(book);
        return new R(flag,flag ? "修改成功" : "修改失败");
    }

    @DeleteMapping("{id}")
    public R delect(@PathVariable Integer id)throws IOException {

        boolean flag= bookService.removeById(id);
        return new R(flag,flag ? "删除成功" : "数据同步失败，自动刷新");
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){

        return new R(true,bookService.getById(id));
    }

   /* @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize){
        IPage<Book> page= bookService.getPage(currentPage, pageSize);
        if (currentPage > page.getPages()){
            page=bookService.getPage((int)page.getPages(),pageSize);
        }
        return new R( true,page);
    }*/

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage,@PathVariable int pageSize, Book book){

        IPage<Book> page= bookService.getPage(currentPage, pageSize,book);
        if (currentPage > page.getPages()){
            page=bookService.getPage((int)page.getPages(),pageSize,book);
        }
        return new R( true,page);
    }

}
